package com.atguigu.gmall.list.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.list.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description: 消息监听
 * @author: JC
 * @date: 2021/11/11 10:05
 */
@Component
public class ListReceiver {

    @Autowired
    private SearchService searchService;

    /**
     * 实现商品上架（es 中上架）
     * @param skuId
     * @param message
     * @param channel
     */
    @RabbitListener(
        bindings = @QueueBinding(
                value = @Queue(value = MqConst.QUEUE_GOODS_UPPER,durable = "true",autoDelete = "false"),
                exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS,durable = "true", autoDelete = "false"),
                key = MqConst.ROUTING_GOODS_UPPER
        )
    )
    @SneakyThrows
    public void upperGoodsListener(Long skuId, Message message, Channel channel){

        // 有消息
        if(skuId != null){
            // 实现上架
            searchService.upperGoods(skuId);
        }
        // 消息确认
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // false: 表示一个一个来确认消息 ，true表示批量确认消息！
        channel.basicAck(deliveryTag,false);

        // 第三个参数：是否重回队列
    }


    /**
     * 实现商品上架（es 中下架）
     * @param skuId
     * @param message
     * @param channel
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = MqConst.QUEUE_GOODS_UPPER,durable = "true",autoDelete = "false"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS,durable = "true", autoDelete = "false"),
                    key = MqConst.ROUTING_GOODS_LOWER
            )
    )
    @SneakyThrows
    public void lowerGoodsListener(Long skuId, Message message, Channel channel){

        // 有消息
        if(skuId != null){
            // 实现上架
            searchService.lowerGoods(skuId);
        }
        // 消息确认
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // false: 表示一个一个来确认消息 ，true表示批量确认消息！
        channel.basicAck(deliveryTag,false);

    }
}
